#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>
#include <pwd.h>
#include <sys/types.h>

#include <stdio.h>
#include <string.h>

static pthread_mutex_t logfile_mutex = PTHREAD_MUTEX_INITIALIZER;
static char *log_filename;
static time_t log_rawtime;
static struct tm * log_timeinfo;
static char str_date_convert[30];
static char str_user_name[30];

void free_logfile()
{
	free(log_filename);
	pthread_mutex_destroy(&logfile_mutex);
}

int init_logfile(char *_log_filename, int argc, char *argv[])
{
	if (pthread_mutex_init(&logfile_mutex, NULL) != 0)
	{
		printf("Error with mutex init (%s)\n", strerror(errno));
		return EXIT_FAILURE;
	};
	
	log_filename = malloc(strlen(_log_filename) + 1);
	strcpy(log_filename, _log_filename);

	struct passwd *tmp_pwd = getpwuid(getuid());
	strcpy(str_user_name, tmp_pwd->pw_name);	
	
    pthread_mutex_lock(&logfile_mutex);	
	
	int fd = -1;
	if ( (fd = open(log_filename, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH)) < 0 )
	{
		printf("Error with write logfile (%s)\n", strerror(errno));
		pthread_mutex_unlock(&logfile_mutex);
		free_logfile();
		return EXIT_FAILURE;
	};

	time (&log_rawtime);
	log_timeinfo = localtime (&log_rawtime);
	sprintf(str_date_convert, "%s", asctime(log_timeinfo));
	trim(str_date_convert);
	
	write(fd, str_date_convert, strlen(str_date_convert));
	sprintf (str_date_convert, " USR(%s), PID (%ld):", str_user_name, (long long)getpid());
	write(fd, str_date_convert, strlen(str_date_convert));
	
	int i;
	for (i = 0; i < argc; i++)
	{
		sprintf(str_date_convert, "%s ", argv[i]);
		write(fd, str_date_convert, strlen(str_date_convert));		
	}
	write(fd, "\n", 1);
	
	close(fd);
	
	pthread_mutex_unlock(&logfile_mutex);
	
	return EXIT_SUCCESS;
}

int write_log(char *str)
{
	return EXIT_SUCCESS;
}